/**
 * 
 */
package tps12.axwax.server.data;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;



import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.users.User;

public class PuzzleStore {
	
	public static final class Factory {
		public PuzzleStore get() {
			return new PuzzleStore();
		}
	}

	final PersistenceManager pm = new PMF().get();
	
	public void close() {
		pm.close();
	}

	@SuppressWarnings("unchecked")
	public List<BarredRectangularPuzzle> list() {
		Query q = pm.newQuery(BarredRectangularPuzzle.class);
		return (List<BarredRectangularPuzzle>) q.execute();
	}
	
	@SuppressWarnings("unchecked")
	public BarredRectangularPuzzle getPuzzle(Key key) {
		Query q = pm.newQuery(BarredRectangularPuzzle.class);
		q.setFilter("key == id");
		q.declareParameters("com.google.appengine.api.datastore.Key id");
		List<BarredRectangularPuzzle> r = (List<BarredRectangularPuzzle>)
			q.execute(key);
		if (r.size() == 0)
			return null;
		else
			return r.get(0);
	}
	
	@SuppressWarnings("unchecked")
	public UserSolution getUserSolution(User user, BarredRectangularPuzzle puzzle) {
		if (user == null) return null;
		
		Query q = pm.newQuery(UserSolution.class);
		q.setFilter("userId == user && puzzle == puzzleKey");
		q.declareParameters("String user, com.google.appengine.api.datastore.Key puzzleKey");
		List<UserSolution> result = (List<UserSolution>)q.execute(
			user.getUserId(), puzzle.getKey());
		if (result.size() != 0)
			return result.get(0);
		else
			return new UserSolution(user, puzzle);
	}
	
	public void save(UserSolution solution) {
		pm.makePersistent(solution);
	}

	public void save(BarredRectangularPuzzle puzzle) {
		pm.makePersistent(puzzle);
	}
}